<template>
  <div class="container">
    <el-card class="report-card">
      <template #header>
        <h3 class="header">患者诊断报告管理</h3>
      </template>

      <div class="patient-list">
        <div class="patient-item header-item">
          <div class="patient-info">
            <div class="info-item id-card">身份证号</div>
            <div class="info-item">姓名</div>
            <div class="info-item">年龄</div>
            <div class="info-item">性别</div>
            <div class="info-item">语言</div>
            <div class="actions">选择操作</div>
          </div>
        </div>

        <div
          v-for="patient in patientStore.patients"
          :key="patient.idCard"
          class="patient-item"
        >
          <div class="patient-info">
            <div class="info-item id-card">{{ patient.idCard }}</div>
            <div class="info-item">{{ patient.name }}</div>
            <div class="info-item">{{ patient.age }}岁</div>
            <div class="info-item">{{ patient.sex }}</div>

            <el-select
              v-model="patient.language"
              placeholder="选择语言"
              size="small"
              style="width: 100px"
            >
              <el-option label="中文" value="ZH" />
              <el-option label="English" value="EN" />
            </el-select>

            <el-select
              v-model="patient.format"
              placeholder="选择格式"
              size="small"
              style="width: 100px"
              :disabled="!patient.reportGenerated"
            >
              <el-option label="PDF" value="pdf" />
              <el-option label="PNG" value="png" />
              <el-option label="HTML" value="html" />
            </el-select>

            <div class="actions">
              <el-button
                type="primary"
                size="small"
                @click="generateReport(patient)"
                :loading="patient.generating"
              >
                生成报告
              </el-button>
              <el-button
                type="success"
                size="small"
                :disabled="!patient.reportGenerated"
                @click="downloadReport(patient)"
              >
                下载报告
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance();
const proxy = instance?.proxy as any;
import { useUserStore } from "@/stores/userStore";
const userStore = useUserStore();
import { usePatientStore } from "@/stores/patientStore";
import { PatientDiagInfo } from "@/types/patient";
import { RequestParams } from "@/types/request";
const patientStore = usePatientStore();

const userData = userStore.getUserData();

const generateReport = async (patient: PatientDiagInfo) => {
  if (!patient.language) {
    proxy.message.warning("请先选择报告语言");
    return;
  }
  try {
    const recordId = patient.recordId;
    const language = patient.language;
    const token = userData.token;
    let result: any = await proxy.request({
      method: "post",
      url:
        proxy.api.reportsGenerate +
        `?recordId=${recordId}&language=${language}`,
      data: {} as RequestParams,
      headers: {
        authentication: token,
      },
    });
    if (!result) {
      return;
    }
    if (result.code === 1) {
      patient.recordId = result.data.id;
      patient.reportGenerated = true;
      proxy.message.success("生成报告成功");
    } else {
      proxy.message.warning("生成报告失败，请检查网络连接");
    }
  } catch (error) {
    proxy.message.error("生成报告失败，请检查网络连接");
  }
};

const downloadReport = async (patient: PatientDiagInfo) => {
  if (!patient.format) {
    proxy.message.warning("请选择报告格式");
    return;
  }
  try {
    const recordId = patient.recordId;
    const format = patient.format;
    const token = userData.token;
    let result: any = await proxy.request({
      method: "get",
      url: proxy.api.reportsDownload + `/${recordId}?format=${format}`,
      headers: {
        authentication: token,
      },
      //保证二进制数据处理方式正确,blob方式，不是文本/json************
      responseType: "blob",
    });
    if (!result) return;
    if (
      result.status === 200 &&
      (result.headers["content-type"]?.includes("application/pdf") ||
        result.headers["content-type"]?.includes("image/png") ||
        result.headers["content-type"]?.includes("text/html"))
    ) {
      const blob = new Blob([result.data], {
        type: result.headers["content-type"],
      });
      const url = URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", `report.${patient.format}`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      proxy.message.success("下载诊断报告成功");
    } else {
      proxy.message.error("下载报告失败，请重新登录");
    }
  } catch (error) {
    proxy.message.error("下载报告失败，请检查网络连接");
  }
};
</script>

<style scoped>
.container {
  /* padding: 20px; */
  margin-top: 20px;
  background: #f5f7fa;
  /* height: 100%; */
}

.header {
  font-size: 1.3rem;
}

.report-card {
  max-width: 100%;
  /* margin: 0 auto; */
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.patient-item {
  margin: 12px 0;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.2s;
}

.patient-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.info-item {
  font-size: 14px;
  color: #606266;
  min-width: 120px;
}

.id-card {
  font-family: monospace;
  color: #409eff;
  font-weight: 500;
}

.actions {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.el-button {
  padding: 8px 16px;
}

.header-item {
  background: #f0f2f5;
  font-weight: bold;
}
</style>
